package util;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import com.bigchun.seeland.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import bean.ContentDataBean;
import myview.CustomProgressDialog;

public class saveImagUtil {

    private static Bitmap thumb;
    private static Context context;
    private static ContentDataBean.DataBean textContent;
    private static CustomProgressDialog customProgressDialog;

    public static void showDiaLog(Context mcontext, final String imgurl, ContentDataBean.DataBean content) {
        context = mcontext;
        customProgressDialog = new CustomProgressDialog(mcontext, "", R.style.CommProgressDialog);
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount=0f;   //取值为0-1之间  1是全黑
//		params.width = 180;//设置进度条的宽度
//		params.height = 180;//设置进度条的宽度
        customProgressDialog.getWindow().setAttributes(params);
        customProgressDialog.show();


        textContent = content;
        getImgBitmap(imgurl);
//        AlertDialog.Builder builder = new AlertDialog.Builder(FxErweimaActivity.this);
       /* final Dialog builder = new Dialog(context, R.style.NormalDialogStyle);
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.dialog_savebolum, null);
        builder.setContentView(v);
        builder.setCanceledOnTouchOutside(true);
        v.setMinimumHeight((int) (ScreenSizeUtils.getInstance(context).getScreenHeight() * 0.23f));
        Window dialogWindow = builder.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (ScreenSizeUtils.getInstance(context).getScreenWidth() * 0.9f);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);
        Button save = (Button) v.findViewById(R.id.bt_save);
        Button  bt_cancle = (Button) v.findViewById(R.id.bt_cancle);

        if (textContent != null){
            save.setText(textContent.getSave());
            bt_cancle.setText(textContent.getCancel());
        }

        //builer.setView(v);//这里如果使用builer.setView(v)，自定义布局只会覆盖title和button之间的那部分
        builder.show();
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                builder.dismiss();
                getImgBitmap(imgurl);

            }
        });
        bt_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                builder.dismiss();
            }
        });*/
    }
    private static void getImgBitmap(final String imgurl){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.e("99999999999999999",thumb+"   0000");
                thumb = utils.returnBitMap3(imgurl);
                if (thumb != null) {
//                                message.arg1 = 4;
                } else {
                    thumb = BitmapFactory.decodeResource(context.getResources(),
                            R.mipmap.icon_default_userlogo);
                }
                Message msg = new Message();
                msg.arg1 = 99;
                handler.sendMessage(msg);

            }}).start();

    }

    /**
     * 将URL转化成bitmap形式
     *
     * @param url
     * @return bitmap type
     */
    public final static Bitmap returnBitMap3(String url) {
        URL myFileUrl;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
            HttpURLConnection conn;
            conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1){
                case 0:

                    break;
                case 1:

                    break;
                case 2:



                    break;
                case 3:


                    break;
                case 4:

                    break;
                case 5:


                    break;
                case 11:

                    break;
                case 99:
                    saveImageToGallery(context,thumb);
                    break;
            }
        }
    };
    public static void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "BianMin");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = "sign_"+System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        String path = file.getAbsolutePath();
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(), path, fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        context.sendBroadcast(intent);
        if (textContent != null){
            if (customProgressDialog!= null){
                if (customProgressDialog.isShowing()){
                    customProgressDialog.dismiss();
                }
            }
            Toast.makeText(context,textContent.getSaved_successfully(),Toast.LENGTH_LONG).show();
        }
    }



}
